from django.shortcuts import render
from bddjango.django import APIResponse, BaseListView, api_decorator, CompleteModelView
from bddjango.adminclass import conv_date_field_str_format
from django.db import models as m
from django.db.models import functions as f
from . import models, serializers, utils
from rest_framework.views import APIView
import os


class Statistics(BaseListView):
    """
    流量分析

    127.0.0.1:8000/api/flow_statistics/Statistics/
    """
    queryset = models.Statistics.objects.all()
    list_serializer_class = serializer_class = serializers.ListStatistics       # 用serializer_class生成wiki
    retrieve_serializer_class = serializers.RetrieveStatistics
    filter_fields = ['count_date', 'mobile']
    order_type_ls = ['-access_date']
    distinct_field_ls = ['access_date']

    # def get(self, request, *args, **kwargs):
    #     access_date_start = self.request.query_params.get('access_date_start')
    #     access_date_end = self.request.query_params.get('access_date_end')
    #     access_date_start, access_date_end = conv_date_field_str_format(access_date_start), conv_date_field_str_format(
    #         access_date_end)
    #     qs = super().get_queryset()
    #     if access_date_start and access_date_end:
    #         qs = qs.filter(access_date__range=[access_date_start, access_date_end])
    #     # queryset = utils.get_statistics_result(qs=qs, order=False, distinct=False, get_serializer_data=False)
    #     ret = utils.get_statistics_result(qs=qs)
    #     status, msg = 200, 'ok'
    #     return APIResponse(ret, status, msg)

    def get_queryset(self):     # get_list_queryset
        """
        这里用annotate添加了一些本不存在于表中的注释字段.
        """
        qs = super().get_queryset()
        access_date_start = self.request.query_params.get('access_date_start')
        access_date_end = self.request.query_params.get('access_date_end')
        access_date_start, access_date_end = conv_date_field_str_format(access_date_start), conv_date_field_str_format(access_date_end)
        if access_date_start and access_date_end:
            qs = qs.filter(access_date__range=[access_date_start, access_date_end])
        queryset = utils.get_statistics_result(qs=qs, order=False, distinct=False, get_serializer_data=False)
        return queryset


class Task(CompleteModelView):
    """
    任务表_测试

    127.0.0.1:8000/api/flow_statistics/Task/1/
    """
    queryset = models.Task
    auto_generate_serializer_class = True
    filter_fields = '__all__'
    post_type_ls = ['list', 'retrieve', 'update']

    def get(self, request, *args, **kwargs):
        # 改变is_active的值
        change_active = request.GET.get('change_active')
        if change_active:
            obj = self.get_object()
            obj.is_active = not obj.is_active
            obj.save()
            return APIResponse(None)

        # 调用填充doc模板程序
        fill_doc_template_and_conv_to_pdf = request.GET.get('fill_doc_template_and_conv_to_pdf')
        if fill_doc_template_and_conv_to_pdf:
            print(fill_doc_template_and_conv_to_pdf)
            obj = self.get_object()

            from django.forms import model_to_dict
            dc_i = model_to_dict(obj)

            # ---- 根据obj填写模板并转为 pdf
            from bddjango import create_dir_if_not_exist
            create_dir_if_not_exist('templates')
            output_dir = os.path.join('templates', 'outputs_docs' )
            create_dir_if_not_exist(output_dir)
            input_dir = os.path.join('templates', 'doc')
            docx_path = os.path.join(input_dir, 'input.docx')

            # --- 确定替换内容context
            import docxtpl
            from docx.shared import Mm
            document = docxtpl.DocxTemplate(docx_path)
            image1_path = 'tempdir/ddd.png'
            insert_image1 = docxtpl.InlineImage(document, image1_path, width=Mm(30), height=Mm(50))

            image2_path = 'tempdir/ddd.png'
            insert_image2 = docxtpl.InlineImage(document, image2_path, width=Mm(50), height=Mm(30))
            # context = {
            #     'name': dc_i.get('summary'),
            #     'school': dc_i.get('content'),
            #     'work_unit': '123aa哈哈哈哈哈aaa213123123',
            #     'portraitPicture': insert_image1,
            #     'signaturePicture': insert_image2,
            # }
            context = {
                'work_unit': dc_i.get('content'),
                'name': dc_i.get('summary'),
                'phone': 18510779999,
                'sex': '男',
                'id_card': 43250311111111,
                'card_type': '大陆身份证',
                'education_degree': '小学生',
                'school': '蓝翔',
                'month': 2,
                'year': 2021,
                "portraitPicture": insert_image1,
                "signaturePicture": insert_image2,
                'created_y': 2021,
                'created_m': 1,
                'created_d': 13,
            }

            # --- 渲染doc替换模板template
            # from .common.docTemplate import ConvDocTemplateToPdf
            # conv_doc_cls = ConvDocTemplateToPdf(context=context, docx_path=docx_path)
            document.render(context=context)
            # conv_doc_cls.run()
            # conv_doc_cls.render()

            if 1:
                # --- 先填写模板, 输出 output_doc
                import docxtpl
                import sys
                # document = conv_doc_cls.daily_docx
                output_doc = f'output_{obj.id}.docx'
                output_path = os.path.join(output_dir, output_doc)
                print(os.path.exists(output_path))

                def delete_file_if_existed(fpath):
                    if os.path.exists(fpath):
                        os.remove(fpath)
                        return True
                    return False
                delete_file_if_existed(fpath=output_path)
                document.save(output_path)

                # --- 判断操作系统版本
                # if sys.platform == 'win32':
                #     prefix = 'start '
                # else:
                #     prefix = 'open '
                #
                # print(prefix)
                file_name = os.path.splitext(output_path)[0]
                output_pdf = file_name + '.pdf'
                delete_file_if_existed(output_pdf)

                # --- docx 转 pdf
                print('=== exist output_path: ', os.path.exists(output_path))
                print('=== exist output_pdf: ', os.path.exists(output_pdf))

                def convert_docx_to_pdf(docx_path):
                    output_dir = os.path.split(docx_path)[0]
                    cmd = f'soffice --headless --invisible --convert-to pdf {docx_path} --outdir {output_dir}'

                    # cmd = f'unoconv -f pdf -e FilterOptions=UTF8,LF {docx_path}'
                    # cmd = f'unoconv -f pdf {docx_path}'
                    res = os.system(cmd)
                    print(res, '---', docx_path)
                    res = not res   # 0则转换pdf成功, 其它失败
                    return res

                res = convert_docx_to_pdf(output_path)
                if res:
                    pdf_file_name = os.path.split(output_pdf)[-1]
                    js_file = 'templates/pdfjs/web/viewer.js'
                    # pdf_file_url = r'..\..\outputs_docs\\' + pdf_file_name
                    pdf_file_url =r"..\..\outputs_docs\{}".format(pdf_file_name)
                    return APIResponse(pdf_file_url, status=201, msg='create pdf successful!')
                else:
                    return APIResponse('', status=404, msg='failed!')

        ret = super().get(request, *args, **kwargs)
        print(ret)
        return ret




